﻿using System;
using System.Collections.Generic;
using Windows.Storage;
using Windows.Storage.Pickers;

namespace Sumc.Client.ModernUI.Helpers
{
    public class SavePickerService : ISavePickerService
    {
        private readonly FileSavePicker fileSavePicker;
        private const string DefaultFileExtension = ".txt";

        public SavePickerService()
        {
            this.fileSavePicker = new FileSavePicker();
        }

        public async void SaveToFile(string text,
            string suggestedFileName,
            string defaultFileExtension = null,
            IEnumerable<KeyValuePair<string, IList<string>>> fileTypes = null)
        {
            this.fileSavePicker.FileTypeChoices.Clear();

            if (fileTypes == null)
            {
                var plainTextFileTypes = new List<string>()
                {
                    DefaultFileExtension
                };
                var keyValue = new KeyValuePair<string, IList<string>>("Plain Text", plainTextFileTypes);
                this.fileSavePicker.FileTypeChoices.Add(keyValue);
            }

            fileSavePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            fileSavePicker.SuggestedFileName = suggestedFileName;
            fileSavePicker.CommitButtonText = "Запази";
            if (defaultFileExtension == null)
            {
                fileSavePicker.DefaultFileExtension = DefaultFileExtension;
            }
            else
            {
                fileSavePicker.DefaultFileExtension = defaultFileExtension;
            }

            var saveFile = await this.fileSavePicker.PickSaveFileAsync();
            if (saveFile != null)
            {
                await FileIO.WriteTextAsync(saveFile, text);
            }
        }
    }
}
